package com.atguigu.gmall.item.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.service.LockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tangsy
 * @Description TODO
 * @date 2022/12/8 18:07
 * @Version 1.0
 */
@Slf4j
@RestController
public class LockController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    LockService lockService;

    @Value("${server.port}")
    String port;

    int i = 0;
    CountDownLatch latch = new CountDownLatch(10000);

    ReentrantLock lock = new ReentrantLock();

    @GetMapping("/incr")
    public Result incrWithDistLock() throws InterruptedException {

        String lock = lockService.lock();

        //1 远程获取一个数字
        String num = redisTemplate.opsForValue().get("num");

        //2 加一
        num = Integer.parseInt(num) + 1 + "";

        //3 修改
        redisTemplate.opsForValue().set("num",num);

        lockService.unlock(lock);

        return Result.ok();
    }



    public Result incrWithLocalLock(){

        log.info("port:{}",port);

//        latch.countDown();
//        i++;
        lock.lock();
        //1 远程获取一个数字
        String num = redisTemplate.opsForValue().get("num");

        //2 加一
        num = Integer.parseInt(num) + 1 + "";

        //3 修改
        redisTemplate.opsForValue().set("num",num);
        lock.unlock();
        return Result.ok();
    }

    @GetMapping("/result")
    public Result I() throws InterruptedException {

        latch.await();
        return Result.ok(i);
    }

}
